import { Flex, Button } from 'antd'
import React, { useState } from 'react'
import { flushSync } from 'react-dom'

const UseStateComponent: React.FC = () => {
  const [count, setCount] = useState<number>(0) // 普通

  // set 属于异步更新即在函数中多次使用 set 会合并操作；
  // const [count, setCount] = useState<number>(() => 0) // 函数式

  // + 1 在 react18之前合成事件为异步更新，原生事件是同步更新
  const handleClick = () => {
    setCount(count + 1)
    setCount(count + 1)
  }
  // + 1 但在 react18 皆为异步更新
  const handleTimeoutClick = () => {
    setTimeout(() => setCount(count + 1))
    setTimeout(() => setCount(count + 1))
  }

  // +2 可以使用函数形式；函数无法合并，即每次返回上一次周期的值；
  const handleFucClick = () => {
    setCount((count) => count + 1)
    setCount((count) => count + 1)
  }

  // +2 强制同步更新
  const handleSyncClick = () => {
    flushSync(() => setCount((count) => count + 1))
    flushSync(() => setCount((count) => count + 1))
  }

  return (
    <Flex gap={5} vertical>
      <p>{count}</p>
      <Button onClick={handleClick}>+ 1</Button>
      <Button onClick={handleTimeoutClick}>setTimeout + 1</Button>
      <Button onClick={handleFucClick}>func + 2</Button>
      <Button onClick={handleSyncClick}>flushSync + 2</Button>
    </Flex>
  )
}
export default UseStateComponent
